package com.jic.market.controller.rest;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.member.exception.AppRuntimeException;
import com.jic.enums.RedisKey;
import com.jic.market.entity.BargainLog;
import com.jic.market.entity.MyBargain;
import com.jic.market.entity.ProductBargain;
import com.jic.market.entity.PromotionBargain;
import com.jic.market.mapper.PromotionMyBargainMapper;
import com.jic.market.request.rest.bargain.*;
import com.jic.market.response.rest.bargain.BargainLogRestResponse;
import com.jic.market.response.rest.bargain.MyBargainRestResponse;
import com.jic.market.response.rest.bargain.ProductBargainInfoRestResponse;
import com.jic.market.response.rest.bargain.ProductBargainRestResponse;
import com.jic.market.service.BargainLogService;
import com.jic.market.service.MyBargainService;
import com.jic.market.service.ProductBargainService;
import com.jic.market.service.PromotionBargainService;
import com.jic.member.request.MememberUserRequest;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.response.ProductAfterInfoByIdResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author wwb
 */
@RestController
@Api(tags = {"砍价H5接口"})
@RequestMapping("/rest/bargain")
@Slf4j
public class BargainRestController {

    @Resource
    private ProductBargainService productBargainService;

    @Resource
    private MyBargainService myBargainService;

    @Resource
    private RedisClientTemplate redisClientTemplate;

    @Resource
    private ProductListApi productListApi;

    @Resource
    private PromotionBargainService promotionBargainService;

    @Resource
    private BargainLogService bargainLogService;

    @Resource
    private PromotionMyBargainMapper myBargainMapper;


    @PostMapping("/listRestPage")
    @ApiOperation("获取砍价活动分页")
    public RestResult<PageResult<ProductBargainRestResponse>> listRestPage(@RequestBody ProductBargainRestRequest request) {
        Page page = new Page();
        page.setLimit(request.getLimit());
        page.setStart(request.getStart());
        return RestResult.success(productBargainService.listRestPage(request, page));
    }


    @PostMapping("/getInvolvedNow")
    @ApiOperation("立即参与")
    public RestResult<ProductBargainInfoRestResponse> getInvolvedNow(@RequestBody GetInvolvedNowRestRequest request) {
        log.info("开始进入立即参与===========》" + request.toString());
        try {
            ProductBargainInfoRestResponse productBargainInfoRestResponse = new ProductBargainInfoRestResponse();
            String userStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + request.getToken());
            MememberUserRequest mMember = JSONArray.parseObject(userStr, MememberUserRequest.class);
            if (mMember == null) {
                throw new AppRuntimeException("9999", "用户未登录");
            }

            //判断是否已经砍价并且是进行中的
            MyBargain myBargain = new MyBargain();
            myBargain.setBargainId(request.getBargainId());
            myBargain.setProductId(request.getProductId());
            myBargain.setMemberId(mMember.getId());
            myBargain.setDeleteFlag(0);
            //已砍金额
            BigDecimal bigDecimal = BigDecimal.ZERO;
            List<MyBargain> myBargainList = myBargainService.query(myBargain);
            if (CollectionUtils.isNotEmpty(myBargainList)) {
                productBargainInfoRestResponse.setIsBargain(1);
                productBargainInfoRestResponse.setMyBargainId(myBargainList.get(0).getId());
                BargainLog bargainLog = new BargainLog();
                bargainLog.setFightMasterId(myBargainList.get(0).getId());
                bigDecimal = bargainLogService.bargainMoneyCount(bargainLog);
                productBargainInfoRestResponse.setAlreadyPrice(bigDecimal);
            } else {
                productBargainInfoRestResponse.setIsBargain(2);
                productBargainInfoRestResponse.setAlreadyPrice(bigDecimal);
            }

            //当前剩余时间
            PromotionBargain promotionBargain = promotionBargainService.queryByPrimaryKey(request.getBargainId());
            if (promotionBargain != null && CollectionUtils.isNotEmpty(myBargainList)) {
                productBargainInfoRestResponse.setTime(getTime(promotionBargain.getTime(),myBargainList.get(0).getCreateTime()));
                productBargainInfoRestResponse.setStartTime(promotionBargain.getStartTime());
                productBargainInfoRestResponse.setEndTime(promotionBargain.getEndTime());
                productBargainInfoRestResponse.setBargainId(promotionBargain.getId());
            } else {
                productBargainInfoRestResponse.setTime(promotionBargain.getEndTime().getTime() - new Date().getTime());
                productBargainInfoRestResponse.setStartTime(promotionBargain.getStartTime());
                productBargainInfoRestResponse.setEndTime(promotionBargain.getEndTime());
                productBargainInfoRestResponse.setBargainId(promotionBargain.getId());
            }


            //多少人正在砍
            MyBargain myBargain1 = new MyBargain();
            myBargain1.setDeleteFlag(0);
            myBargain1.setBargainId(request.getBargainId());
            myBargain1.setProductId(request.getProductId());
            productBargainInfoRestResponse.setBargainNum(myBargainMapper.queryPageCount(myBargain1));

            //商品信息
            RestResult<ProductAfterInfoByIdResponse> responseRestResult =
                    productListApi.queryProductInfoById(myBargain.getProductId());
            if (null != responseRestResult && null != responseRestResult.getData()) {
                productBargainInfoRestResponse.setProductId(myBargain.getProductId());
                productBargainInfoRestResponse.setChineseName(responseRestResult.getData().getChineseName());
                productBargainInfoRestResponse.setUrl(responseRestResult.getData().getPictureUrl());
                productBargainInfoRestResponse.setPrice(responseRestResult.getData().getSalePriceWithTax());
                productBargainInfoRestResponse.setCondent(responseRestResult.getData().getContent());
                productBargainInfoRestResponse.setAvailableStock(responseRestResult.getData().getAvailableStock());

                //最低价格
                ProductBargain productBargain = new ProductBargain();
                productBargain.setBargainId(request.getBargainId());
                productBargain.setProductId(request.getProductId());
                productBargain.setDeleteFlag(0L);
                List<ProductBargain> productBargainList = productBargainService.query(productBargain);
                if (CollectionUtils.isNotEmpty(productBargainList)) {
                    productBargainInfoRestResponse.setFloorPrice(productBargainList.get(0).getFloorPrice());
                }

                //当前价格
                productBargainInfoRestResponse.setNowPrice(responseRestResult.getData().getSalePriceWithTax().subtract(bigDecimal));

            }
            return RestResult.success(productBargainInfoRestResponse);
        } catch (Exception e) {
            log.error("立即参与砍价活动查询失败===========》", e);
            return RestResult.error("9999", "立即参与砍价活动查询失败");
        }
    }


    @PostMapping("/getMyBargain")
    @ApiOperation("我的砍价")
    public RestResult<PageResult<MyBargainRestResponse>> getMyBargain(@RequestBody MyBargainQueryRestRequest request) {
        Page page = new Page();
        page.setLimit(request.getLimit());
        page.setStart(request.getStart());
        return RestResult.success(myBargainService.listRestPage(request, page));
    }

    @PostMapping("/getMyBargainInfo")
    @ApiOperation("找人帮砍/继续砍价")
    public RestResult<ProductBargainInfoRestResponse> getMyBargainInfo(@RequestBody MyBargainRestRequest request) {
        ProductBargainInfoRestResponse productBargainInfoRestResponse = new ProductBargainInfoRestResponse();

        MyBargain myBargain = myBargainService.queryByPrimaryKey(request.getId());
        if (myBargain != null) {
            productBargainInfoRestResponse.setBargainId(myBargain.getBargainId());
            productBargainInfoRestResponse.setProductId(myBargain.getProductId());

            //获取最低价
            ProductBargain productBargain = new ProductBargain();
            productBargain.setBargainId(myBargain.getBargainId());
            productBargain.setProductId(myBargain.getProductId());
            productBargain.setDeleteFlag(0L);
            List<ProductBargain> productBargainList = productBargainService.query(productBargain);
            if (CollectionUtils.isNotEmpty(productBargainList)) {
                productBargainInfoRestResponse.setFloorPrice(productBargainList.get(0).getFloorPrice());
            }

            //已砍价格
            BargainLog bargainLog = new BargainLog();
            bargainLog.setFightMasterId(myBargain.getId());
            BigDecimal bigDecimal1 = bargainLogService.bargainMoneyCount(bargainLog);
            if (bigDecimal1 == null) {
                productBargainInfoRestResponse.setAlreadyPrice(BigDecimal.ZERO);
            } else {
                productBargainInfoRestResponse.setAlreadyPrice(bigDecimal1);
            }

            //商品信息
            RestResult<ProductAfterInfoByIdResponse> responseRestResult =
                    productListApi.queryProductInfoById(myBargain.getProductId());
            if (null != responseRestResult && null != responseRestResult.getData()) {
                productBargainInfoRestResponse.setChineseName(responseRestResult.getData().getChineseName());
                productBargainInfoRestResponse.setUrl(responseRestResult.getData().getPictureUrl());
                productBargainInfoRestResponse.setPrice(responseRestResult.getData().getSalePriceWithTax());

                //当前价格
                productBargainInfoRestResponse.setNowPrice(responseRestResult.getData().getSalePriceWithTax().subtract(productBargainInfoRestResponse.getAlreadyPrice()));

                //当前剩余时间
                PromotionBargain promotionBargain = promotionBargainService.queryByPrimaryKey(myBargain.getBargainId());
                if (productBargain != null) {
                    productBargainInfoRestResponse.setTime(getTime(promotionBargain.getTime(),myBargain.getCreateTime()));
                }
            }
        }
        return RestResult.success(productBargainInfoRestResponse);
    }


    @PostMapping("/getMyBargainLog")
    @ApiOperation("砍价记录")
    public RestResult<PageResult<BargainLogRestResponse>> getMyBargainLog(@RequestBody MyBargainRestRequest request) {
        Page page = new Page();
        page.setLimit(request.getLimit());
        page.setStart(request.getStart());
        return RestResult.success(bargainLogService.listRestPage(request, page));
    }


    @PostMapping("/helpBargain")
    @ApiOperation("立即砍价/继续砍价")
    public RestResult<MyBargainRestResponse> helpBargain(@RequestBody MyBargainSaveRestRequest request) {
        String userStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + request.getToken());
        MememberUserRequest mMember = JSONArray.parseObject(userStr, MememberUserRequest.class);
        if (mMember == null) {
            return RestResult.error("9999", "用户未登录");
        }
        return RestResult.success(myBargainService.helpBargain(request));
    }


    //获取活动结束时间戳
    public long getTime(Integer hours,Date createTime) {
        if (hours == null || createTime==null) {
            return -1;
        }
        long l = createTime.getTime() + (long) hours * 60 * 60*1000 - new Date().getTime();
        return l;
    }
}
